package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dao.UserDao;
import com.example.domain.Result;
import com.example.domain.TableData;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;


@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public Result findByUsernameAndPassword(String username, String password, HttpSession session) {
        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(!StringUtils.isEmpty(username), User::getUsername, username).eq(!StringUtils.isEmpty(password), User::getPassword, password);
        User user = userDao.selectOne(qw);
        if (user != null && session != null) {
            session.setAttribute("user", user);
            return Result.success(user);
        }

        return Result.error("用户名密码有误");
    }

    @Override
    public TableData<User> getPage(Integer page, Integer limit, String username) {
//
//        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.like(!StringUtils.isEmpty(username),User::getUsername,username);
//
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.like(!StringUtils.isEmpty(username), "username", username);

        IPage<User> ipage = new Page(page, limit);
        IPage<User> userIPage = userDao.selectPage(ipage, queryWrapper);
        TableData<User> tableData = new TableData<>();
        tableData.setCount(userIPage.getTotal());
        tableData.setCode(0);
        tableData.setMsg("");

        tableData.setData(userIPage.getRecords());
        return tableData;
    }

    @Override
    public Result register(String username, String password) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(!StringUtils.isEmpty(username), User::getUsername, username);


        if (userDao.selectOne(lambdaQueryWrapper) != null) {
            return Result.error("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        int i = userDao.insert(user);
        if (i > 0) {
            return Result.success("注册成功");
        }
        return Result.error("注册失败");
    }


}
